

package com.scalar.chiptrack.users.actions;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.Level;
import com.scalar.chiptrack.users.LevelAccess;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.users.forms.AccessLevelSetupForm;



public class AccessLevelSetupAction extends ChipTrackAction {

    private HashMap m_errors = new HashMap();

    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws Exception {

        HttpSession session = request.getSession();
        if ((session == null) || (session.getAttribute (SessionKeys.USER_KEY) == null)) {
            return (mapping.findForward("login"));
        }

        AccessLevelSetupForm levelSetupForm = (AccessLevelSetupForm) form;
        int levelId = levelSetupForm.getLevelId();
        String levelName = null;
        if( levelSetupForm.getLevelName() != null)
        {
            levelName = levelSetupForm.getLevelName().trim();
        }

        Enumeration paramNames = request.getParameterNames();
        HashMap levelAccessMap = new HashMap();
        LevelAccess levelAccess = null;

        String functionIdParam = null;
        String functionIdParamValue = null;

        int functionId = -1;
        int groupId = -1;
        String action = null;

        int firstIndex = -1;
        int secondIndex = -1;
        int lastIndex = -1;

        if((levelName != null) && (levelName.trim().length() != 0))
        {
                ArrayList levelList = UserDAO.loadAllLevels();

                if (levelList != null )
                {
                    int levelListSize = levelList.size();
                    Level level = null;
                    for (int i=0; i<levelListSize; i++)
                    {
                        level = (Level) levelList.get (i);
                        if( levelName.equalsIgnoreCase(level.getName()))
                        {
                            m_errors.put ("Access level name is already exists please enter another name", null);
                        }
                    }
                }
        }

        while (paramNames.hasMoreElements()) {

            functionIdParam = (String) paramNames.nextElement();

            if (functionIdParam.startsWith ("FUNCTION_ID") == true) {

                functionIdParamValue = request.getParameter(functionIdParam);

                if ("on".equalsIgnoreCase (functionIdParamValue) == true) {

                    try {

                        firstIndex = functionIdParam.indexOf(',');
                        secondIndex = functionIdParam.indexOf (',', firstIndex+1);
                        lastIndex = functionIdParam.lastIndexOf(',');

                        functionId = Integer.parseInt (functionIdParam.substring ((firstIndex+1), secondIndex));
                        groupId = Integer.parseInt (functionIdParam.substring ((secondIndex+1), lastIndex));
                        action = functionIdParam.substring (lastIndex+1);

                        levelAccess = (LevelAccess) levelAccessMap.get (""+functionId);
                        if (levelAccess == null) {
                            levelAccess = new LevelAccess();
                            levelAccess.setFunctionId (functionId);
                            levelAccess.setGroupId (groupId);
                            levelAccess.setLevelId (levelId);
                            levelAccessMap.put (""+functionId, levelAccess);

                        }

                        if (action.equalsIgnoreCase ("view") == true) {
                            levelAccess.setView (true);
                        }
                        else if (action.equalsIgnoreCase ("modify") == true) {
                            levelAccess.setModify (true);
                        }
                        else if (action.equalsIgnoreCase ("delete") == true) {
                            levelAccess.setDelete (true);
                        }
                    }
                    catch (Exception e) {
                        e.printStackTrace(System.err);
                        m_errors.put ("Exception while parsing the data, Couldnot store data into database", null);
                    }
                }
            }

        }

        if (m_errors.isEmpty() == false) {
            request.setAttribute(SessionKeys.ERROR_MESSAGES, m_errors);
            m_errors = new HashMap();   // re-set
            return (mapping.findForward ("failure"));
        }

        try {
            if ((levelName != null) && (levelName.trim().length() != 0)) {  // Insert a new row for this level
                levelId = -1;
            }
            UserDAO.storeLevelAccessList (levelId, levelName, levelAccessMap.values().iterator());

            HashMap info = new HashMap();
            info.put ("Access Level information has been saved successfully", null);
            request.setAttribute(SessionKeys.INFO_MESSAGES, info);
        }

        catch (ScalarException se) {
            se.printStackTrace (System.err);
            m_errors.put ("Exception while storing the data into database", null);
        }

        if (m_errors.isEmpty() == false) {
            request.setAttribute(SessionKeys.ERROR_MESSAGES, m_errors);
            m_errors = new HashMap();   // re-set
            return (mapping.findForward ("failure"));
        }

        return (mapping.findForward("success"));
    }
}